import axios from 'axios'
import { ElMessage } from 'element-plus'
import { mockRequest } from './mock'

// 创建 axios 实例
const service = axios.create({
  baseURL: '',
  timeout: 10000,
  withCredentials: true
})

// 是否使用模拟数据
const useMock = true

// 请求拦截器
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.log('err', error)
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

// 封装请求方法
const request = (url, method, data) => {
  // 如果使用模拟数据，则调用 mockRequest
  if (useMock) {
    return mockRequest(url, data)
  }
  
  // 否则发送真实 API 请求
  const config = {
    url,
    method
  }
  
  if (method === 'get') {
    config.params = data
  } else {
    config.data = data
  }
  
  return service(config)
}

// 流程定义 API
export const processDefinitionApi = {
  // 获取流程定义列表
  getList: (params) => request('/process-definition', 'get', params),
  
  // 启动流程实例
  startInstance: (definitionId, data) => request(`/process-definition/${definitionId}/start`, 'post', data),
  
  // 激活流程定义
  activate: (definitionId) => request(`/process-definition/${definitionId}/activate`, 'post'),
  
  // 挂起流程定义
  suspend: (definitionId) => request(`/process-definition/${definitionId}/suspend`, 'post'),
  
  // 删除流程定义
  delete: (definitionId) => request(`/process-definition/${definitionId}`, 'delete')
}

// 流程实例 API
export const processInstanceApi = {
  // 获取流程实例列表
  getList: (params) => request('/process-instance', 'get', params),
  
  // 激活流程实例
  activate: (instanceId) => request(`/process-instance/${instanceId}/activate`, 'post'),
  
  // 挂起流程实例
  suspend: (instanceId) => request(`/process-instance/${instanceId}/suspend`, 'post'),
  
  // 删除流程实例
  delete: (instanceId) => request(`/process-instance/${instanceId}`, 'delete')
}

// 任务 API
export const taskApi = {
  // 获取任务列表
  getList: (params) => request('/task', 'get', params),
  
  // 完成任务
  complete: (taskId, data) => request(`/task/${taskId}/complete`, 'post', data),
  
  // 认领任务
  claim: (taskId, userId) => request(`/task/${taskId}/claim`, 'post', { userId }),
  
  // 转办任务
  transfer: (taskId, userId) => request(`/task/${taskId}/transfer`, 'post', { userId })
}

// 仪表盘 API
export const dashboardApi = {
  // 获取统计数据
  getStats: () => request('/dashboard/stats', 'get'),
  
  // 获取最近活动
  getActivities: () => request('/dashboard/activities', 'get')
}

export default {
  processDefinitionApi,
  processInstanceApi,
  taskApi,
  dashboardApi
} 